package com.ssyan.prototype.deepclone;

import java.io.*;

/**
 * @author ssyan
 * @Description TODO
 * @create 2021/8/28 1:48
 * @Version 1.0
 */
public class DeepPrototype implements Serializable,Cloneable {

    public String name;//String 类型
    public DeepCloneableTarget deepCloneableTarget;//引用类型

    //完成深拷贝
    //方式一：使用clone
    @Override
    protected DeepPrototype clone() throws CloneNotSupportedException {
        DeepPrototype deep = null;
        //这里是默认对基本数据类型和字符串的克隆
        deep = (DeepPrototype) super.clone();

        //对引用类型的属性，进行单独处理
        deep.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

        return deep;
    }

    //深拷贝 - 方式2 通过对象的序列化实现（推荐）
    public DeepPrototype deepClone() {

        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);//当前这个对象以对象流的方式输出

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype copy = (DeepPrototype)ois.readObject();

            return copy;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
